package person.drf.shop.product.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableConfigurationProperties(CacheProperties.class)  //引入配置文件的内容
public class MyCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        // K V 序列化机制
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis cachePropertiesRedis = cacheProperties.getRedis();
        //让配置文件所有配置都生效
        if(cachePropertiesRedis.getTimeToLive()!=null){
            config = config.entryTtl(cachePropertiesRedis.getTimeToLive());
        }
        if(cachePropertiesRedis.getKeyPrefix()!=null){
            config = config.prefixKeysWith(cachePropertiesRedis.getKeyPrefix());
        }
        if(!cachePropertiesRedis.isCacheNullValues()){
            config = config.disableCachingNullValues();
        }
        if(!cachePropertiesRedis.isUseKeyPrefix()){
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
